import random
from pathlib import Path

import addict
import toml

from ._typing import TeamName
from .soldier import Soldier
from .tank import Tank

config = addict.Dict(toml.load(Path(__file__).parent / "config.toml"))


class Team:
    r"""队伍类实现，一共可能有两种类型：

    * 蓝队
    * 红队

    :param name: 队伍名称
    """

    tanks: list[Tank]
    soldiers: list[Soldier]

    def __init__(self, name: TeamName) -> None:
        assert name in TeamName.__args__
        match name:
            case "Blue":
                y_min = 0
                if config.random_start_pos is True:
                    y_max = config.map.height / 3
                else:
                    y = y_min
            case "Red":
                y_max = config.map.height
                if config.random_start_pos is True:
                    y_min = config.map.height * 2 / 3
                else:
                    y = y_max
        self.name = name
        self.n_tank = config.team.get("n_{}_tank".format(self.name.lower()))
        self.tanks = []
        for i in range(self.n_tank):
            if config.random_start_pos is True:
                x = random.uniform(0, config.map.width)
                y = random.uniform(y_min, y_max)
            else:
                x = (
                    config.map.width / 2
                    + config.map.width / 5 * ((i + 1) // 2) * (-1) ** i
                )
            t = Tank(x, y, self.name)
            self.tanks.append(t)
        self.n_soldier = config.team.get("n_{}_soldier".format(self.name.lower()))
        self.soldiers = []
        for i in range(self.n_soldier):
            if config.random_start_pos is True:
                x = random.uniform(0, config.map.width)
                y = random.uniform(y_min, y_max)
            else:
                x = (
                    config.map.width / 2
                    + config.map.width / 20 * ((i + 1) // 2) * (-1) ** i
                )
            s = Soldier(x, y, self.name)
            self.soldiers.append(s)

    @property
    def alive(self) -> list[bool]:
        """指示队伍所有坦克是否灭亡"""
        return any([t.alive for t in self.tanks]) or any(
            [s.alive for s in self.soldiers]
        )
